Page({
  data: {
    ctx: null,
    canvas: null,
    isDrawing: false,
    lastX: 0,
    lastY: 0
  },

  onLoad() {
    wx.nextTick(() => {
      this.initCanvas();
    });
  },

  async initCanvas() {
    try {
      const query = wx.createSelectorQuery();
      query.select('#signature-canvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          if (!res || !res[0] || !res[0].node) {
            console.error('Canvas node not found');
            return;
          }

          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          
          const dpr = wx.getSystemInfoSync().pixelRatio || 1;
          const { width, height } = res[0];
          
          canvas.width = width * dpr;
          canvas.height = height * dpr;
          ctx.scale(dpr, dpr);
          
          ctx.strokeStyle = '#000000';
          ctx.lineWidth = 4;
          ctx.lineCap = 'round';
          ctx.lineJoin = 'round';
          
          this.setData({ 
            canvas,
            ctx
          });
        });
    } catch (error) {
      console.error('Canvas initialization error:', error);
      wx.showToast({
        title: '初始化失败，请重试',
        icon: 'none'
      });
    }
  },

  handleTouchStart(e) {
    if (!this.data.ctx) return;
    const { x, y } = e.touches[0];
    this.setData({
      isDrawing: true,
      lastX: x,
      lastY: y
    });
  },

  handleTouchMove(e) {
    if (!this.data.isDrawing || !this.data.ctx) return;
    const { x, y } = e.touches[0];
    const { ctx, lastX, lastY } = this.data;
    
    ctx.beginPath();
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(x, y);
    ctx.stroke();
    
    this.setData({
      lastX: x,
      lastY: y
    });
  },

  handleTouchEnd() {
    this.setData({
      isDrawing: false
    });
  },

  handleClear() {
    const { ctx, canvas } = this.data;
    if (!ctx || !canvas) return;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
  },

  async handleConfirm() {
    const { canvas } = this.data;
    if (!canvas) {
      wx.showToast({
        title: '签名内容为空',
        icon: 'none'
      });
      return;
    }
    
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.canvasToTempFilePath({
          canvas,
          success: (res) => resolve(res.tempFilePath),
          fail: (error) => {
            console.error('Save signature error:', error);
            reject(error);
          }
        });
      });

      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      prevPage.setData({
        signatureImage: tempFilePath
      });
      wx.navigateBack();
    } catch (error) {
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none'
      });
    }
  }
}); 